<?php
/**
 * Created by PhpStorm.
 * User: 图图
 * Date: 2021-5-11
 * Time: 9:11
 */

namespace app\web\controller;

use app\common\service\CombineService;
use app\web\validate\CombineValidate;
use think\Db;
use app\common\model\Combine as CombineModel;
use app\common\model\Project;
use app\common\model\CombineGoods;
use app\common\model\Goods;

/**
 * 组合下单
 * Class Combine
 * @package app\manage\admin
 */
class Combine extends Auth
{

    /**
     * 组合下单列表
     * @return mixed
     * @throws \think\Exception
     */
    public function index()
    {

        $post = $this->request->post();
        $limit = $post['limit'] ?? 10;
        $data_list = CombineModel::order('sort asc, id desc')->paginate($limit)->toArray();
        $userInfo = $this->userInfo;
        $room_data = Db::name('qt_room_type')
            ->where(['store_id' => $userInfo['store_id'], 'status' => '1'])
            ->order('sort asc')
            ->column('id,name','id');
        foreach ($data_list['data'] as $k => &$v) {
            $v['block_type_name'] =
                $v['block_type'] == 1 ? "点钟" : $v['block_type'] == 2 ? "排钟" : $v['block_type'] == 3 ? "call钟" : $v['block_type'] == 4 ? "call钟" : "选钟";
            $v['room_type_name'] = $room_data[$v['room_type']] ?? '';
            $goods_list = CombineService::getCombineGoods($v['id']);
            $v['goods_list'] = !empty($goods_list) ? $goods_list : [];
        }

        // 分页数据
        $this->result('查询成功', $data_list, 200);
    }

    /**
     * 添加组合下单
     * @return mixed
     * @throws \think\Exception
     */
    public function add()
    {
        if ($this->request->isPost()) {

            $post = $this->request->post();
            $validate = new CombineValidate();
            if (!$validate->scene('add')->check($post)) {
                $this->result($validate->getError(), '', 204);
            }
            $userInfo = $this->userInfo;
            $project_info = Project::get($post['project_id']);
            $post['project_name'] = $project_info['name'];
            $post['store_id'] = $userInfo['store_id'];
            $post['create_time'] = time();
            $goods_list = $post['goods_list'];
            if (CombineModel::get(['name' => $post['name']])){
                $this->result('组合下单名已经存在', '', 204);
            }
            try{
                Db::startTrans();
                if ($model = CombineModel::create($post)) {
                    if (!empty($post['goods_list'])) {
                        foreach ($goods_list as $key => &$val) {
                            $goods_info = Goods::get($val['id']);
                            unset($val['id']);
                            $val['goods_id'] = $goods_info['id'];
                            $val['goods_name'] = $goods_info['name'];
                            $val['combine_id'] = $model['id'];
                            $val['store_id'] = $userInfo['store_id'];
                            if($goods_info['status'] == '0'){
                                $this->result('【'.$goods_info->getAttr('name').'】不可售，无法添加组合下单', '', 204);
                            }
                        }
                        Db::name('qt_data_combine_goods')->insertAll($goods_list);
                    }
                }
                //更新订单状态
                Db::commit();
            }catch (Exception $exception){
                Db::rollback();
                $this->result('新增失败', '', 204);
            }
            $this->result('新增成功', '', 200);

        }
        $this->result('无效的请求', '', 204);
    }


    /**
     * 编辑设置组合下单
     * @param null $id
     * @return mixed
     * @throws \think\Exception
     */
    public function edit()
    {
        if ($this->request->isPost()) {

            $post = $this->request->post();
            $validate = new CombineValidate();
            if (!$validate->scene('edit')->check($post)) {
                $this->result($validate->getError(), '', 204);
            }

            if (empty($post['id'])) {
                $this->result('Id字段必填', '', 204);
            }
            $userInfo = $this->userInfo;
            $project_info = Project::get($post['project_id']);
            $data['project_name'] = $project_info['name'];
            $data['update_time'] = time();
            CombineModel::where('id', $post['id'])->update($post);

            //echo "</pre>";
            //print_r($post['goods_list']);
            //exit;
            if (!empty($post['goods_list'])) {
                $goods_list = $post['goods_list'];
                foreach ($goods_list as $key => &$val) {
                    $goods_info = Goods::get($val['id']);
                    unset($val['id']);
                    $val['goods_id'] = $goods_info['id'];
                    $val['goods_name'] = $goods_info['name'];
                    $val['combine_id'] = $post['id'];
                    $val['store_id'] = $userInfo['store_id'];
                    if($goods_info['status'] == '0'){
                        $this->result('【'.$goods_info->getAttr('name').'】不可售，无法添加组合下单', '', 204);
                    }
                }

                Db::name('qt_data_combine_goods')->where(['combine_id'=>$post['id']])->delete();
                Db::name('qt_data_combine_goods')->insertAll($goods_list);
            }else {

                $goods = Db::name('qt_data_combine_goods')->where(['combine_id'=>$post['id']])->find();
                if (!empty($goods)) {

                    Db::name('qt_data_combine_goods')->where(['combine_id'=>$post['id']])->delete();
                }
            }
            $this->result('编辑成功', '', 200);

        }
        $this->result('无效的请求', '', 204);
    }

    /**
     * 获取项目列表
     */
    public function getProjectList(){

        $list = Project::field('id,name')->select()->toArray();
        $this->result('请求成功', $list, 200);
    }

    /**
     * 获取编辑组合详情
     */
    public function getEditInfo () {

        if ($this->request->isPost()) {

            $id = $this->request->post('id');
            $info = Db::name('qt_data_combine')->where(['id'=>$id])->find();
            if (empty($info)) {
                $this->result('没有查询到对应ID的数据', '', 204);
            }
            $userInfo = $this->userInfo;
            $room_type = explode(',',$info['room_type']);
            $block_type = explode(',',$info['block_type']);
            $info['block_type'] = $block_type;
            $info['room_type'] = $room_type;
            $block_type_name = '';

            $block_type_data = [
                1=>"点钟,",
                2=>"排钟,",
                3=>"加钟,",
                4=>"call钟,",
                5=>"选钟,",
            ];
            foreach ($block_type as $k => $v) {
                $block_type_name .= $block_type_data[$v];
            }
            $info['block_type_name'] = rtrim($block_type_name,',');
            $room_data = Db::name('qt_room_type')
                ->where(['store_id' => $userInfo['store_id'], 'status' => '1'])
                ->whereIn('id',$room_type)
                ->column('name');
            $info['room_type_name'] = implode(',',$room_data);
            $info['goods_list'] = CombineService::getCombineGoods($id);
            $this->result('请求成功', $info, 200);
        }

        $this->result('无效的请求', '', 204);
    }


    /**
     * 删除组合下单
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function removeCombine(){
        if ($this->request->isPost()) {

            $id = $this->request->post('id');
            $info = CombineModel::get($id);
            if (!empty($info)) {
                Db::name('qt_data_combine')->where(['id'=>$id])->delete();
                Db::name('qt_data_combine_goods')->where(['combine_id'=>$id])->delete();

                $this->result('删除成功', '', 200);
            }else {
                $this->result('没有查询到对应ID的数据', '', 204);
            }
        }

        $this->result('无效的请求', '', 204);

    }

    /**
     * 添加套餐关联的商品或者项目
     * @param null $id
     * @return mixed
     * @throws \think\Exception
     */
    public function addGoods()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();

            $userInfo = $this->userInfo;
            $CombineGoods = CombineGoods::get(['combine_id' => $data['combine_id'], 'goods_id' => $data['goods_id']]);
            if ($CombineGoods) {
                $CombineGoods->number = intval($CombineGoods['number'] + $data['number']);
                $result = $CombineGoods->save();
            } else {
                $goods_info = Goods::get($data['goods_id']);
                $data['goods_name'] = $goods_info['name'];
                $data['store_id'] = $userInfo['store_id'];
                $result = CombineGoods::create($data);
            }

            if ($result) {
                $this->result('添加成功', '', 200);
            }else {
                $this->result('添加失败', '', 204);
            }
        }

        $this->result('无效的请求', '', 204);
    }

    /**
     * 获取所有商品列表
     */
    public function getGoodsList() {

        $goods = CombineService::getGoods();
        $this->result('查询成功', $goods, 200);

    }

    /**
     * 获取组合包含商品列表
     * @param $id
     * @return mixed
     * @throws \think\Exception
     */
    public function goodsLists()
    {
        if ($this->request->isPost()) {
            $post = $this->request->post();
            $data = CombineService::getCombineGoods($post['combine_id']);
            if ($data) {
                $this->result('添加成功', $data, 200);
            }else {
                $this->result('添加失败', '', 204);
            }
        }

        $this->result('无效的请求', '', 204);

    }

    /**
     * 修改商品数量
     * @param $id [商品ID]
     */
    public function changeNum()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $combineGoods = CombineGoods::get(['id' => $data['id']]);
            if ($combineGoods) {
                $combineGoods->number = $data['number'];
                $combineGoods->save();
                $this->result('添加成功', '', 200);
            }else {
                $this->result('添加失败', '', 204);
            }
        }

        $this->result('无效的请求', '', 204);
    }

    /**
     * 删除组合下商品信息
     *
     * @throws \Exception
     */
    public function remove()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $combineGoods = CombineGoods::get(['id' => $data['id']]);
            if ($combineGoods) {
                $combineGoods->delete();
                $this->result('删除成功', '', 200);
            }else {
                $this->result('删除失败', '', 204);
            }
        }

        $this->result('无效的请求', '', 204);
    }

}